//
// Created by lzc on 2023/1/14.
//

#ifndef AOS_SOCK_H
#define AOS_SOCK_H
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"

#define BUF_SIZE 4096
char buf[BUF_SIZE];

char* recStr(int sockfd) {
    bzero(buf, sizeof(buf));
    recv(sockfd, buf, BUF_SIZE, 0);
    return buf;
}

void sendStr(int sockfd, const char *str) {
    send(sockfd, str, strlen(str), 0);
    usleep(1);
}

int recFile(int sockfd, const char *filepath) {
    if (strcmp(recStr(sockfd), "err") == 0) {
        printf("fail to download %s\n", filepath);
        return 0;
    }

    printf("start downloading %s...\n", filepath);
    size_t n;
    FILE *file = fopen(filepath, "wb");

    while ((n = recv(sockfd, buf, BUF_SIZE, 0)) > 0) {
        fwrite(buf, sizeof(char), n, file);
    }
    if (n<0) {
        printf("Error receiving file\n");
        return 0;
    }
    fclose(file);
    printf("Ok %s\n", filepath);
    return 1;
}

int sendFile(int sockfd, const char *filepath){
    FILE *file;
    if ((file = fopen(filepath, "rb")) == NULL){
        sendStr(sockfd, "err");
        return 0;
    }

    sendStr(sockfd, "ok");
    size_t n;
    while ((n = fread(buf, sizeof(char), BUF_SIZE, file)) > 0) {
        send(sockfd, buf, n, 0);
    }

    if (n < 0) {
        printf("Error sending file\n");
        return 0;
    }
    fclose(file);
    return 1;
}

#endif //AOS_SOCK_H
